import { DataTypes, Model, Sequelize } from "sequelize";

/**
 * 用户模型接口
 */
export interface UserAttributes {
  id?: number;
  username: string;
  password_hash: string;
  salt: string;
  status?: number;
  last_login_at?: Date;
  last_login_ip?: string;
  login_count?: number;
  created_at?: Date;
  updated_at?: Date;
}

/**
 * 用户模型类
 */
export class User extends Model<UserAttributes> implements UserAttributes {
  public id!: number;
  public username!: string;
  public password_hash!: string;
  public salt!: string;
  public status!: number;
  public last_login_at!: Date;
  public last_login_ip!: string;
  public login_count!: number;
  public created_at!: Date;
  public updated_at!: Date;
}

/**
 * 初始化用户模型
 */
export function initUserModel(sequelize: Sequelize): typeof User {
  User.init(
    {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true,
        comment: "用户ID，主键自增"
      },
      username: {
        type: DataTypes.STRING(50),
        allowNull: false,
        unique: true,
        comment: "用户名，唯一索引"
      },
      password_hash: {
        type: DataTypes.STRING(255),
        allowNull: false,
        comment: "密码哈希值，使用bcrypt加密"
      },
      salt: {
        type: DataTypes.STRING(32),
        allowNull: false,
        comment: "密码盐值，增强安全性"
      },
      status: {
        type: DataTypes.TINYINT,
        defaultValue: 1,
        comment: "用户状态：1-正常，0-禁用，2-待激活"
      },
      last_login_at: {
        type: DataTypes.DATE,
        allowNull: true,
        comment: "最后登录时间"
      },
      last_login_ip: {
        type: DataTypes.STRING(45),
        allowNull: true,
        comment: "最后登录IP地址，支持IPv6"
      },
      login_count: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        comment: "登录次数统计"
      },
      created_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        comment: "创建时间"
      },
      updated_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        comment: "更新时间"
      }
    },
    {
      sequelize,
      tableName: "users",
      modelName: "User",
      timestamps: true,
      underscored: true,
      indexes: [
        {
          fields: ["username"],
          name: "idx_username"
        },
        {
          fields: ["status"],
          name: "idx_status"
        },
        {
          fields: ["created_at"],
          name: "idx_created_at"
        }
      ],
      comment: "用户基础信息表"
    }
  );

  return User;
}
